<?php


namespace app\common\model\workflow;

use think\Exception;
use think\facade\Db;
use think\facade\Request;
use think\Model;

class Workflow extends Model
{
    protected $name = 'wf_workflow';
    protected $json = ['content'];
    protected $jsonAssoc = true;

    public static function list($user){
        $creator = Request::param('creator','','trim');
        $flowName = Request::param('flowName','','trim');
        $flowNo = Request::param('flowNo','','trim');
        $searchType = Request::param('searchType','','trim');

        $where = [];
        if(!empty($name)){
            $where[] = ['a.creator_name','like','%'.$creator.'%'];
        }
        if(!empty($flowName)){
            $where[] = ['a.name','like','%'.$flowName.'%'];
        }
        if(!empty($flowNo)){
            $where[] = ['a.flow_no','=',$flowNo];
        }
        $query = Db::name('wf_workflow')->alias('a');
        switch ($searchType){
            case 0:// 我发起的
                $where[] = ['a.creator_id','=',$user['id']];
                break;
            case 1://待我审核的
                $where[] = ['a.audit_id','find in set',$user['id']];
                $where[] = ['a.state','=', '1'];
                break;
            case 2://我已审批的
                $where[] = ['b.scope_id','=',$user['id']];
                $query->join('wf_node_record b','a.id = b.flow_id and b.record_type = 2 and b.node_type = 1')
                    ->group('a.id');
                break;
            case 3://抄送我的
                $where[] = ['b.scope_id','=',$user['id']];
                $query->join('wf_node_record b','a.id = b.flow_id and b.record_type = 1 and b.node_type = 2')
                    ->group('a.id');
                break;
        }
        $list = $query->withAttr('creator_time', function($value, $data) {
            return $value > 0 ? date('Y-m-d H:i:s',$value) : '';
        })->withAttr('complete', function($value, $data) {
            return $value > 0 ? date('Y-m-d H:i:s',$value) : '';
        })->where($where)->order('a.id desc')->paginate(Request::post('limit'));
        return $list;
    }

    public function getCreatorTimeAttr($value)
    {
        return Date('Y-m-d H:i:s',$value);
    }

    public function nodes()
    {
        return $this->hasMany(Node::class,'flow_id');
    }

    public function records()
    {
        return $this->hasMany(NodeRecord::class,'flow_id');
    }

    public function scopes()
    {
        return $this->hasMany(NodeScope::class,'flow_id');
    }

}